/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package interfaz.plantillas;

import admin.Admin;
import dialogos.seleccion.SeleccionGenerica;
import entidades.NotaEntrada;
import entidades.Sesion;
import entidades.Usuario;
import exceptions.ConfigFTPIncorrecta;
import exceptions.ValoresIncompletosException;
import exceptions.ValoresIncorrectosException;
import interfaces.PlantillaRegistro;
import interfaces.controlestablas.ControlUsuarios;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import javax.swing.JOptionPane;
import utiles.JFileChooserHelper;
import utiles.ListenerProgreso;
import utiles.UtilesCalendar;
import utils.ftp.Upload;

/**
 *
 * @author fcarou
 */
public class PlantillaNotaEntrada extends javax.swing.JPanel implements PlantillaRegistro
{
    private NotaEntrada notaEntrada;
    private File archivo;
    private Thread uploader;

    /**
     * Creates new form PlantillaNotaEntrada
     */
    public PlantillaNotaEntrada(NotaEntrada notaEntrada)
    {
        this.notaEntrada = notaEntrada;
        
        initComponents();
    }

    public NotaEntrada getNotaEntrada()
    {
        return notaEntrada;
    }

    public void setNotaEntrada(NotaEntrada notaEntrada)
    {
        this.notaEntrada = notaEntrada;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        campoFecha = new javax.swing.JTextField();
        boxFecha = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        campoCantidadFojas = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        campoReferencia = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        botonSeleccionar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        botonAdjuntar = new javax.swing.JButton();
        barraUpload = new javax.swing.JProgressBar();

        jLabel1.setText("Número ingreso");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${notaEntrada.numeroIngreso}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel2.setText("Fecha");

        boxFecha.setText("Obtener fecha del sistema");
        boxFecha.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyTyped(java.awt.event.KeyEvent evt)
            {
                boxFechaKeyTyped(evt);
            }
        });

        jLabel3.setText("Cantidad fojas");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${notaEntrada.cantidadFojas}"), campoCantidadFojas, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel4.setText("Referencia");

        jLabel5.setText("Destinatario: ");

        botonSeleccionar.setText("Seleccionar");
        botonSeleccionar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonSeleccionarActionPerformed(evt);
            }
        });

        jLabel6.setText("Archivo: ");

        botonAdjuntar.setText("Adjuntar");
        botonAdjuntar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonAdjuntarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(barraUpload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextField1)
                    .addComponent(campoFecha)
                    .addComponent(campoCantidadFojas)
                    .addComponent(campoReferencia)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botonSeleccionar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botonAdjuntar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(boxFecha, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(0, 186, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(boxFecha)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoCantidadFojas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoReferencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(botonSeleccionar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(botonAdjuntar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                .addComponent(barraUpload, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void boxFechaKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_boxFechaKeyTyped
    {//GEN-HEADEREND:event_boxFechaKeyTyped
        if (evt.getKeyChar() == '\n')
            boxFecha.setSelected(!boxFecha.isSelected());
    }//GEN-LAST:event_boxFechaKeyTyped

    private void botonSeleccionarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonSeleccionarActionPerformed
    {//GEN-HEADEREND:event_botonSeleccionarActionPerformed
        SeleccionGenerica dialogoSeleccion = new SeleccionGenerica(null, true, new ControlUsuarios());
        dialogoSeleccion.setVisible(true);
        
        Object objeto = dialogoSeleccion.getSeleccion();
        
        if (objeto != null)
            notaEntrada.setDestino((Usuario) objeto);
    }//GEN-LAST:event_botonSeleccionarActionPerformed

    private void botonAdjuntarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonAdjuntarActionPerformed
    {//GEN-HEADEREND:event_botonAdjuntarActionPerformed
        if (uploader != null && uploader.isAlive())
        {
            if (JOptionPane.showConfirmDialog(this, "Ya se esta subiendo otro archivo.\nSeguro quiere seleccionar otro?", "Error", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
                return;
            else
                uploader.interrupt();
        }
            
        archivo = JFileChooserHelper.tomarArchivo(this);
        
        if (archivo == null)
            return;
        
        try
        {
            Upload up = new Upload(new ListenerProgreso(barraUpload), archivo);
            uploader = new Thread(up);
            //up.conectar();
            uploader.start();
        }
        catch(ConfigFTPIncorrecta ex)
        {
            JOptionPane.showMessageDialog(this, "Error, el cliente FTP no ha sido configurado.");
        } 
    }//GEN-LAST:event_botonAdjuntarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar barraUpload;
    private javax.swing.JButton botonAdjuntar;
    private javax.swing.JButton botonSeleccionar;
    private javax.swing.JCheckBox boxFecha;
    private javax.swing.JTextField campoCantidadFojas;
    private javax.swing.JTextField campoFecha;
    private javax.swing.JTextField campoReferencia;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextField1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    @Override
    public Object getDato() throws ValoresIncorrectosException, ValoresIncompletosException
    {
        Calendar fecha = (boxFecha.isSelected()) ? Calendar.getInstance() : UtilesCalendar.construirCalendar(campoFecha.getText());
        
        if (fecha == null)
            throw new ValoresIncorrectosException("La fecha ingresada es invalida.\nUtilice el formato [DD/MM/AAAA]");
        
        notaEntrada.setFecha(fecha);
        
        if (notaEntrada.getCantidadFojas() == 0 || notaEntrada.getFecha() == null || notaEntrada.getNumeroIngreso().equals(""))
            throw new ValoresIncompletosException("Debe llenar todos los campos.");
        
        if (archivo == null)
            throw new ValoresIncompletosException("No ha seleccionado un archivo.");
        
        if (barraUpload.getValue() != barraUpload.getMaximum())
            throw new ValoresIncompletosException("Debe esperar que el archivo adjunto sea subido.");
        
        notaEntrada.setArchivo(archivo.getName());
        notaEntrada.setTamArchivo(archivo.length());
        
        Sesion sesion = Admin.getInstance().getAdminSesion().getSesion();
        if (sesion == null || sesion.getUsuario() == null)
            throw new ValoresIncorrectosException("No hay un usuario logueado.");
        
        notaEntrada.setOrigen(sesion.getUsuario());
        
        return notaEntrada;
    }
}
